package work.fram;

import com.google.common.base.Joiner;
import lombok.extern.java.Log;

@Log
public class SqlMaker {

    public final static int TYPE_INSERT = 1;
    public final static int TYPE_UPDATE = 2;
    public final static int TYPE_DELETE = 3;
    public final static int TYPE_SELECT = 4;

    private KeyValueMapper keyValueMapper;

    public void setKeyValueMapper(KeyValueMapper keyValueMapper) {
        this.keyValueMapper = keyValueMapper;
    }

    private String table;

    public SqlMaker() {
    }

    public SqlMaker(String table) {
        this.table = table;
    }

    public KeyValueMapper createKeyValueMapper() {
        this.keyValueMapper = new KeyValueMapper();
        return keyValueMapper;
    }

    public void setTable(String table) {
        this.table = table;
    }

    private String sql;

    public boolean make(int type, String... condition) {

        if (table == null) {
            log.warning("未设置表名,无法生成sql");
            return false;
        }


        switch (type) {
            case TYPE_INSERT:
                if (keyValueMapper == null) {
                    log.warning("未绑定键值对映射器,无法生成sql");
                    return false;
                }
                if (!keyValueMapper.make(",", null)) {
                    return false;
                }
                sql = "insert into " + table + "(" + keyValueMapper.getKeyString() + ")" + " values(" + keyValueMapper.getValueString() + ");";
                return true;
            case TYPE_UPDATE:
                if (keyValueMapper == null) {
                    log.warning("未绑定键值对映射器,无法生成sql");
                    return false;
                }
                if (!keyValueMapper.make(",", "=")) {
                    return false;
                }
                sql = "update " + table + " set " + keyValueMapper.getKvString();
                if (condition.length > 0) {
                    sql += " where " + Joiner.on("and").join(condition);
                }

                sql += ";";

                return true;

            case TYPE_DELETE:
                sql = "delete from " + table;
                if (condition.length > 0) {
                    sql += " where " + Joiner.on("and").join(condition);
                }
                sql += ";";
                return true;
        }
        return false;
    }

    public String getSql() {
        return sql;
    }
}
